﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace EOrm
{
    /// <summary>
    /// Orm映射工具类型
    /// </summary>
    public static class OrmTool
    {
        /// <summary>
        /// 根据对象值和是否可空将对象转换为数据库可以接受的字符串格式
        /// </summary>
        /// <param name="val">对象值</param>
        /// <param name="isNullable">是否可空</param>
        /// <returns>数据库可以接受的字符串</returns>
        /// <exception cref="ArgumentException">变量错误异常</exception>
        public static string ConvertValue(object val, bool isNullable)
        {
            if (val != null)
            {
                return GetDbValStr(val);
            }
            else
            {
                if (isNullable)
                {
                    return "NULL";
                }
                else
                {
                    throw new ArgumentException("非空属性列不能传入空值", "val");
                }
            }
        }

        /// <summary>
        /// 对象转换为数据库可接受的字符串，用于组合sql语句
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns>字符串</returns>
        private static string GetDbValStr(object obj)
        {
            string res = "";
            if (obj == null)
            {
                throw new ArgumentNullException("obj", "要转换的对象为空");
            }
            else
            {
                if (obj is DateTime)
                {
                    DateTime dt = (DateTime)obj;
                    res = string.Format("\'{0}\'", dt.ToString("yyyy-MM-dd HH:mm:ss"));
                }
                else if (obj is string)
                {
                    res = string.Format("\'{0}\'", obj.ToString());
                }
                else
                {
                    res = GetStringNotNull(obj.ToString());
                }
                if (GetListCharNotNull(res.ToList()).FindAll(a => a == '\'').Count() % 2 != 0)
                {
                    int index = res.LastIndexOf('\'');
                    res = res.Insert(index, "\'");
                }
            }

            return res;
        }

        /// <summary>
        /// 获取非空的字符集合
        /// </summary>
        /// <param name="chars">可空的字符集合</param>
        /// <returns>非空的字符集合</returns>
        private static List<char> GetListCharNotNull(List<char> chars)
        {
            if (chars == null)
            {
                return new List<char>();
            }
            return chars;
        }

        /// <summary>
        /// 获取非空的字符串
        /// </summary>
        /// <param name="chars">可空的字符串</param>
        /// <returns>非空的字符串</returns>
        private static string GetStringNotNull(string str)
        {
            if (str == null)
            {
                return "";
            }
            return str;
        }
    }
}
